import React, { createContext, ReactElement } from 'react';

import { State, Action, Context } from './types';
import actions, { getReload } from './actions';
import Provider from '../../components/Provider';

export const initialState: State = {
  lesson: {
    nextId: 0,
    status: 0,
    nextTime: '',
    leftSeconds: 0,
    lessons: [],
    courseName: '',
    grade: '',
    subject: ''
  },
  isFetchFailed: false
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_LESSON': {
      return {
        ...state,
        lesson: action.value,
        isFetchFailed: false
      };
    }
    case 'FETCH_FAILED':
      return { ...state, isFetchFailed: true };
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      reload={getReload}
      {...props}
    />
  );
};
